﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TN_CMS.Admin.Controllers;
using TN_CMS.Domain.Abstract;
using TN_CMS.Domain.Concrete;
using TN_CMS.Domain.Entities;

namespace TN_CMS.Admin.Filters
{
    public class TNAdminAuthAttribute : AuthorizeAttribute
    {
        // private readonly ISysAdminRepository _sysAdminRepository;

        public TNAdminAuthAttribute()
        {

        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var TNController = (TNController)filterContext.Controller;

            string controller = filterContext.RouteData.Values["controller"].ToString().ToLower();
            string action = filterContext.RouteData.Values["action"].ToString().ToLower();
            string returnUrl = filterContext.RequestContext.HttpContext.Request.Url.AbsoluteUri;

            if (!(controller == "common"
                || controller == "account"
                || controller == "home"
                || action.Contains("upload")
            ))
            {
                if (TNController.SysAdmin != null)
                {
                    var EFSysAdminRepository = new EFSysAdminRepository();
                    var EFSysRoleRepository = new EFSysRoleRepository();
                    var sysAdmin = EFSysAdminRepository.GetDetail(TNController.SysAdmin.Id);
                    var lstSysFeature = new List<SysFeature>();

                    if (sysAdmin.SysRoles != null && sysAdmin.SysRoles.Count > 0)
                    {
                        foreach (var item in sysAdmin.SysRoles)
                        {
                            lstSysFeature.AddRange(item.SysFeatures.ToList());
                        }
                    }

                    var hasPermissionSysFeature = lstSysFeature.Where(m => m.Link.ToLower() == string.Format("/{0}", controller)).ToList();
                    bool hasPermission = hasPermissionSysFeature != null && hasPermissionSysFeature.Count > 0 ? true : false;

                    if (!hasPermission)
                    {
                        // this._authenticationService.SignOut();
                        TNController.HttpContext.Session.Abandon();

                        filterContext.Result = new RedirectResult("/account/login?returnUrl=" + returnUrl);
                    }
                }
                else
                {
                    filterContext.Result = new RedirectResult("/account/login?returnUrl=" + returnUrl);
                }
            }
        }
    }
}